//
//  CardTableView.m
//  TSListDemo
//
//  Created by qian on 2020/11/16.
//  Copyright © 2020 dvlproad. All rights reserved.
//

#import "CardTableView.h"
#import <SDWebImage/SDWebImage.h>
#import "CardTableViewHeader.h"
#import "CardImageTableViewCell.h"
#import "CardTextTableViewCell.h"

#import "CardTableViewCellInfoModel.h"


@interface CardTableView () <UITableViewDataSource, UITableViewDelegate> {
    
}
@property (nonatomic, strong, readonly) NSArray<CardTableViewCellInfoModel *> *dataModels;

@end


@implementation CardTableView

- (void)dealloc {
    [self removeObserver:self forKeyPath:@"contentOffset"];
}

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style {
    self = [super initWithFrame:frame style:style];
    if (self) {
        [self registerClass:[CardImageTableViewCell class] forCellReuseIdentifier:@"CardImageTableViewCell"];
        [self registerClass:[CardTextTableViewCell class] forCellReuseIdentifier:@"CardTextTableViewCell"];
        
        self.dataSource = self;
        self.delegate = self;
        
        self.estimatedRowHeight = 80.0f;
        self.rowHeight = UITableViewAutomaticDimension;
        
        CGFloat screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
        CGFloat collectionViewHeight = screenHeight - 80;
        CGFloat cellHeight = collectionViewHeight - 80;
        
        CardTableViewHeader *tableViewHeader = [[CardTableViewHeader alloc] initWithFrame:CGRectMake(0, 0, 0, cellHeight)];
        self.tableHeaderView = tableViewHeader;
        
        
        [self addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
    }
    return self;
}

#pragma mark - Setter
- (void)setTableHeaderViewHeight:(CGFloat)tableHeaderViewHeight {
    _tableHeaderViewHeight = tableHeaderViewHeight;

    CGRect tableViewHeaderFrame = CGRectMake(0, 0, 0, tableHeaderViewHeight);
    self.tableHeaderView.frame = tableViewHeaderFrame;
}

//#pragma mark - layoutSubviews
//- (void)layoutSubviews {
//    [super layoutSubviews];
//    NSLog(@"layoutSubviews %@", NSStringFromClass([self class]));
//
//    // Error:不能再这里设置，sectionTitle显示不到正确位置
//    CGRect tableViewHeaderFrame = CGRectMake(0, 0, 200, self.frame.size.height);
//    self.tableHeaderView.frame = tableViewHeaderFrame;
//}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if (object == self && [keyPath isEqualToString:@"contentOffset"]) {
        NSValue *contentOffsetValue = change[@"new"];
        CGPoint contentOffset = [contentOffsetValue CGPointValue];
        //NSLog(@"contentOffset = %@", NSStringFromCGPoint(contentOffset));
 
        CGFloat offset = contentOffset.y + CGRectGetHeight(self.frame);
        CGFloat size = self.contentSize.height;
        CGFloat maxYPercentCurrent = offset/size;                                                   // maxY当前滑道的百分比
        CGFloat maxYPercentWhenMinYisZero = CGRectGetHeight(self.frame)/self.contentSize.height;    // 当minY=0时候，maxY滑道的百分比
        !self.didScrollPercent ?: self.didScrollPercent(maxYPercentCurrent, maxYPercentWhenMinYisZero);
    }
}


#pragma mark - Setter
- (void)setInfoModel:(CQUserDetailModel *)infoModel {
    _infoModel = infoModel;
    
    CardTableViewHeader *tableViewHeader = (CardTableViewHeader *)self.tableHeaderView;
    tableViewHeader.user = infoModel;
    
    // cell部信息
    NSMutableArray<CardTableViewCellInfoModel *> *cellInfoModels = [[NSMutableArray alloc] init];
    // imageCellModels
    NSMutableArray<CardTableViewCellInfoModel *> *imageCellModels = [[NSMutableArray alloc] init];
    for (CQUserDetailImageModel *imageModel in infoModel.imageDataModels) {
        CardTableViewCellInfoModel *imageCellModel = [[CardTableViewCellInfoModel alloc] init];
        imageCellModel.imageUrl = imageModel.url;
        [imageCellModels addObject:imageCellModel];
    }
    // qaCellModels
    NSMutableArray<CardTableViewCellInfoModel *> *qaCellModels = [[NSMutableArray alloc] init];
    for (CQUserDetaiQAModel *qaModels in infoModel.desDataModels) {
        CardTableViewCellInfoModel *qaCellModel = [[CardTableViewCellInfoModel alloc] init];
        qaCellModel.title = qaModels.question;
        qaCellModel.des = qaModels.answer;
        [qaCellModels addObject:qaCellModel];
    }
    for (CQUserDetaiQAModel *qaModels in infoModel.dailyDataModels) {
        CardTableViewCellInfoModel *qaCellModel = [[CardTableViewCellInfoModel alloc] init];
        qaCellModel.title = qaModels.question;
        qaCellModel.des = qaModels.answer;
        [qaCellModels addObject:qaCellModel];
    }
    for (CQUserDetaiQAModel *qaModels in infoModel.wishDataModels) {
        CardTableViewCellInfoModel *qaCellModel = [[CardTableViewCellInfoModel alloc] init];
        qaCellModel.title = qaModels.question;
        qaCellModel.des = qaModels.answer;
        [qaCellModels addObject:qaCellModel];
    }
    
    NSInteger imageCount = imageCellModels.count;
    NSInteger qaCount = qaCellModels.count;
    if (imageCount > qaCount) {
        for (NSInteger i = 0; i < imageCount; i++) {
            if (i < qaCount) {
                [cellInfoModels addObject:imageCellModels[i]];
                [cellInfoModels addObject:qaCellModels[i]];
            } else {
                [cellInfoModels addObject:imageCellModels[i]];
            }
        }
    } else {
        for (NSInteger i = 0; i < qaCount; i++) {
            if (i < imageCount) {
                [cellInfoModels addObject:imageCellModels[i]];
                [cellInfoModels addObject:qaCellModels[i]];
            } else {
                [cellInfoModels addObject:qaCellModels[i]];
            }
        }
    }
    
    _dataModels = cellInfoModels;
    [self reloadData];
}

#pragma mark - UITableViewDataSource & UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger iRowCount = self.dataModels.count;
    return iRowCount;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSString *indexTitle = [NSString stringWithFormat:@"section:%zd", section];
    return indexTitle;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    BOOL isImageCell = indexPath.item % 2 == 0;
//    if (isImageCell) {
//        return 200;
//    } else {
//        return 60;
//    }
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CardTableViewCellInfoModel *dataModel = self.dataModels[indexPath.row];
    BOOL isImageCell = dataModel.imageUrl != nil;
    if (isImageCell) {
        CardImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CardImageTableViewCell" forIndexPath:indexPath];
        NSURL *imageURL = [NSURL URLWithString:dataModel.imageUrl];
        [cell.backgroundImageView sd_setImageWithURL:imageURL completed:nil];
        return cell;
    } else {
        CardTextTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CardTextTableViewCell" forIndexPath:indexPath];
        UIColor *randomColor = [UIColor colorWithRed:arc4random()%255/256.0f green:arc4random()%255/256.0f blue:arc4random()%255/256.0f alpha:1.0f];
        cell.contentView.backgroundColor = randomColor;
        
        cell.titleLabel.text = dataModel.title;
        cell.detailLabel.text = dataModel.des;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSLog(@"点击了%zd-%zd", indexPath.section, indexPath.row);
}


#pragma mark - Touch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
